#!/bin/bash

# GuessWho Cloud Code Deployment Script
# Deploy Parse Cloud Code to Back4App

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Configuration
APP_ID="NwrNwnQTDLxBoneM8ziHiyJCQ56miSCLEWYpPk4i"
MASTER_KEY="vC3r01pXmWcMfM4lz2mCCjcJ4GgRghWoqi27E9GP"  # Replace with your actual master key
SERVER_URL="https://parseapi.back4app.com/"

echo -e "${GREEN}🚀 GuessWho Cloud Code Deployment${NC}"
echo "=================================="

# Check if we're in the correct directory
if [ ! -f "main.js" ] || [ ! -f "package.json" ]; then
    echo -e "${RED}❌ Error: main.js or package.json not found. Please run this script from the cloud directory.${NC}"
    exit 1
fi

# Install dependencies
echo -e "${YELLOW}📦 Installing dependencies...${NC}"
npm install

if [ $? -ne 0 ]; then
    echo -e "${RED}❌ Failed to install dependencies${NC}"
    exit 1
fi

# Update Parse configuration in main.js and matchPoolJob.js
echo -e "${YELLOW}⚙️  Updating Parse configuration...${NC}"
sed -i "s/NwrNwnQTDLxBoneM8ziHiyJCQ56miSCLEWYpPk4i/${APP_ID}/g" main.js
sed -i "s/NwrNwnQTDLxBoneM8ziHiyJCQ56miSCLEWYpPk4i/${APP_ID}/g" matchPoolJob.js

# Create .parsecirc file for Parse CLI
echo -e "${YELLOW}🔧 Creating Parse configuration...${NC}"
cat > .parsecirc << EOF
{
  "applications": {
    "GuessWho": {
      "applicationId": "${APP_ID}",
      "masterKey": "${MASTER_KEY}",
      "serverURL": "${SERVER_URL}"
    }
  }
}
EOF

# Check if Parse CLI is installed
if ! command -v parse &> /dev/null; then
    echo -e "${YELLOW}📥 Installing Parse CLI...${NC}"
    npm install -g @parse/cli
fi

# Deploy cloud code
echo -e "${YELLOW}🚀 Deploying cloud code to Back4App...${NC}"
parse deploy

if [ $? -eq 0 ]; then
    echo -e "${GREEN}✅ Cloud code deployed successfully!${NC}"
    echo -e "${GREEN}🎉 Your GuessWho cloud functions are now live!${NC}"
    
    echo -e "\n${YELLOW}📋 Next steps:${NC}"
    echo "1. Update your MASTER_KEY in the script"
    echo "2. Test deployment with health check:"
    echo "   Parse.Cloud.run('healthCheck')"
    echo "3. Start match pool cron:"
    echo "   Parse.Cloud.run('startMatchPoolCron')"
    
else
    echo -e "${RED}❌ Deployment failed${NC}"
    echo -e "${YELLOW}Please check your Back4App credentials and try again${NC}"
    exit 1
fi

# Clean up
echo -e "${YELLOW}🧹 Cleaning up...${NC}"
rm -f .parsecirc

echo -e "${GREEN}✨ Deployment complete!${NC}"
